package co.fitstart.admin.web.controller.user;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.content.UserSearch;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.UserService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.entity.user.User;

/**
 * 
 * @author Jack
 *
 */
@Controller
@RequestMapping("/users")
@MenuSetting("menu-user")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    @Qualifier("dataService")
    private DataService<User> dataService;
    
    @Autowired
    private UserService userService;
    
    /**
     * List all users
     * 
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET)
    @MenuSetting("submenu-user-management")
    public ModelAndView list(HttpServletRequest request, Page page){
        
        ModelAndView modelAndView = new ModelAndView("user/user-list");
        
        List<User> users = userService.list(page);
        
        modelAndView.addObject("users", users);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * Display search panel
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search(){
        return "user/user-search";
    }
    
    
    /**
     * Do search news
     * 
     * @param userSearch
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method=RequestMethod.GET, params="filter")
    @MenuSetting("submenu-user-management")
    public ModelAndView onSearch(UserSearch userSearch,
                                 HttpServletRequest request,
                                 Page page){
        
        ModelAndView modelAndView = new ModelAndView("user/user-list");
        
        List<User> users = dataService.search(User.class, userSearch, page);
        
        modelAndView.addObject("refer", "search");
        
        modelAndView.addObject("users", users);
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * Display user view
     * 
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}" , method = RequestMethod.GET)
    @MenuSetting("submenu-user-management")
    public ModelAndView view(@PathVariable("userId") Long userId){
        
        ModelAndView modelAndView = new ModelAndView("user/user-view");
        
        User user = dataService.load(User.class, userId);
        
        modelAndView.addObject("user", user);
        
        return modelAndView;
    }
    
    /**
     * @return
     */
    @RequestMapping(value = "/exist", method = RequestMethod.GET)
    @MenuSetting("submenu-user-management")
    public String exist() {
        return "user/user-mobile";
    }
    
    /**
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/exist", method = RequestMethod.POST)
    @MenuSetting("submenu-user-management")
    public @ResponseBody String onExist(@RequestParam("mobile") String mobile) {
        
        Result result = new Result();
        
        try {
            
            User user = userService.load(mobile);
            result.success().data("url", "/users/" + user.getId() + "/input")
                            .message("用户存在, 等待跳转进入录入页面");
            
        } catch (Exception e) {
            logger.trace("#existUser() - user not exist, mobile is []", mobile);
            result.fail().data("url", "/users")
                         .message("用户不存在");
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}/input", method = RequestMethod.GET)
    @MenuSetting("submenu-user-management")
    public ModelAndView input(@PathVariable("userId") Long userId) {
        
        ModelAndView modelAndView = new ModelAndView("user/user-input");
        
        modelAndView.addObject("user", dataService.load(User.class, userId));
        
        return modelAndView;
    }
    
    /**
     * @param userId
     * @param user
     * @return
     */
    @RequestMapping(value = "/{userId}/input", method = RequestMethod.PATCH)
    @MenuSetting("submenu-user-management")
    public @ResponseBody String onInput(@PathVariable("userId") Long userId,
                                        @Preloading("id") User user) {

        Result result = new Result();
        
        try {
            
            dataService.update(user.editInputTime(new Date()));
            result.success().message("录入档案成功");
            
        } catch (Exception e) {
            logger.error("#onInput() - input user archives fail, exception is [{}]", e);
            result.fail().message("录入档案失败");
        }
        
        return JsonUtils.toJsonString(result);
        
    }
    
    /**
     * 小程序解绑
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}/unbind", method = RequestMethod.GET)
    @MenuSetting("submenu-user-management")
    public ModelAndView unbind(@PathVariable("userId") Long userId) {
        
        ModelAndView modelAndView = new ModelAndView("user/user-unbind");
        
        modelAndView.addObject("userId", userId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}/unbind", method = RequestMethod.PATCH)
    @MenuSetting("submenu-user-management")
    public @ResponseBody String onUnbind(@PathVariable("userId") Long userId) {
        Result result = new Result();
        
        try {
            User user = userService.load(userId);
            
            userService.unbind(user);
            
            result.success().message("小程序解绑成功");
            
        } catch (Exception e) {
            logger.error("#onUnbind() - unbind fail, exception is [{}]", e);
            result.fail().message("小程序解绑失败");
        }
        
        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}/disable", method = RequestMethod.GET)
    @MenuSetting("submenu-user-management")
    public ModelAndView disable(@PathVariable("userId") Long userId) {
        
        ModelAndView modelAndView = new ModelAndView("user/user-disable");
        
        modelAndView.addObject("userId", userId);
        
        return modelAndView;
    }

    /**
     * 
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}/disable", method = RequestMethod.PATCH)
    @MenuSetting("submenu-user-management")
    public @ResponseBody String onDisable(@PathVariable("userId") Long userId) {
        Result result = new Result();
        
        try {
            User user = userService.load(userId);
            
            userService.disable(user);
            
            result.success().message("删除成功");
            
        } catch (BusinessException e) {
            result.fail().message(e.getMessage());
        } catch (Exception e) {
            logger.error("#onDisable() - disable fail, exception is [{}]", e);
            result.fail().message("删除失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
